//
//  CityPostionExtViewController.m
//  MemberProject
//
//  Created by mac on 15/4/30.
//  Copyright (c) 2015年 MAC OS X. All rights reserved.
//

#import "CityPostionExtViewController.h"
#import "CityPositionCollectionViewCell.h"
#import "HotCityPositionTableViewCell.h"
#import <BaiduMapAPI/BMKLocationService.h>
#import <BaiduMapAPI/BMKGeocodeSearch.h>
#import <BaiduMapAPI/BMapKit.h>
@interface CityPostionExtViewController ()<UITableViewDataSource,UITableViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,HotCityPositionTableViewCellDelegate>
@property(strong,nonatomic)NSDictionary *data;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(strong,nonatomic)NSArray *keys;

@property(strong,nonatomic)NSArray *hotData;

@property(strong,nonatomic)NSArray *positionData;

@property(strong,nonatomic)BMKLocationService *locService;

@property(strong,nonatomic)BMKGeoCodeSearch *geoCodeSearch;


@end

@implementation CityPostionExtViewController
-(void)dealloc{
    [self.locService stopUserLocationService];
    self.locService=nil;
    self.geoCodeSearch.delegate=nil;
    self.geoCodeSearch=nil;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title=@"城市列表";
//    UISegmentedControl *segmentedControl=[[UISegmentedControl alloc]initWithItems:@[@"国内",@"海外"]];
//    segmentedControl.frame=CGRectMake(0, 0, 100, 25);
//    self.navigationItem.titleView=segmentedControl;
    
    
    UIBarButtonItem *leftBarButton=[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleBordered target:self action:@selector(chickLeftBarButton:)];
    self.navigationItem.leftBarButtonItem=leftBarButton;
    
    
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [self.tableView registerNib:[UINib nibWithNibName:@"HotCityPositionTableViewCell" bundle:nil] forCellReuseIdentifier:@"HotCellIdentifier"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CellIdentifier"];
    NSString *filePath=[[NSBundle mainBundle]pathForResource:@"cityPosition" ofType:@"plist"];
    NSDictionary *dic=[[NSDictionary alloc]initWithContentsOfFile:filePath];
    
    self.data=dic;
    
    NSArray *keys=[dic allKeys];
    NSMutableArray *arrM=[[NSMutableArray alloc]initWithObjects:@"#",@"$", nil];
    [arrM addObjectsFromArray:[keys sortedArrayUsingSelector:@selector(compare:)]];
    self.keys=arrM;
    
//    self.hotData=@[@{@"name":@"上海市"},@{@"name":@"北京市"},@{@"name":@"佛山市"},@{@"name":@"广州市"}];
    
    [self analyzeHotData];
    
    self.positionData=@[@{@"name":@"定位中"}];
}

-(void)analyzeHotData{
    NSMutableArray *arrM=[NSMutableArray array];
    NSArray *keys=@[@"S",@"B",@"F",@"G"];
    NSArray *citys=@[@"上海市",@"北京市",@"佛山市",@"广州市"];
    for(int i=0;i<citys.count;i++){
        NSString *key=keys[i];
        NSString *city=citys[i];
        NSArray *arr=self.data[key];
        NSString *preStr=[NSString stringWithFormat:@"name LIKE[cd] '*%@*'",city];
        NSPredicate *pre=[NSPredicate predicateWithFormat:preStr];
        NSArray *resultArr=[arr filteredArrayUsingPredicate:pre];
        if(resultArr.count!=0){
            NSMutableDictionary *dicM=[[NSMutableDictionary alloc]initWithDictionary:[resultArr lastObject]];
            [arrM addObject:dicM];
        }
    }
    self.hotData=arrM;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //开始百度定位
    [self startUpdatingLocation];

}

-(void)chickLeftBarButton:(UIBarButtonItem *)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - startUpdatingLocation
-(void)startUpdatingLocation{
    if ([CLLocationManager locationServicesEnabled]){
        NSLog(@"定位服务正常！");
//        [SVProgressHUD showWithStatus:@"定位中"];
//        [BMKLocationServicesetLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
        //指定最小距离更新(米)，默认：kCLDistanceFilterNone
//        [BMKLocationServicesetLocationDistanceFilter:100.f];
        
        //初始化BMKLocationService
        if(self.locService==nil){
            self.locService = [[BMKLocationService alloc]init];
            self.locService.delegate = self;
        }
        //启动LocationService
        [self.locService startUserLocationService];
        
        if(self.geoCodeSearch==nil){
            self.geoCodeSearch=[[BMKGeoCodeSearch alloc]init];
            self.geoCodeSearch.delegate=self;
        }
    }else{
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *str=[[NSString alloc]initWithFormat:@"请打开系统设备中“隐私-定位服务”，允许“%@”使用您的位置",infoDictionary[@"CFBundleDisplayName"]];
        
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
        NSLog(@"定位服务异常");
    }
}

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [self.locService stopUserLocationService];
    BMKReverseGeoCodeOption *option=[[BMKReverseGeoCodeOption alloc]init];
    option.reverseGeoPoint=userLocation.location.coordinate;
    [self.geoCodeSearch reverseGeoCode:option];
    //NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
}

- (void)didFailToLocateUserWithError:(NSError *)error{
    [self.locService stopUserLocationService];
    self.geoCodeSearch.delegate=nil;
    self.geoCodeSearch=nil;
    [SVProgressHUD showErrorWithStatus:@"定位失败"];
    self.positionData=@[@{@"name":@"定位失败"}];
    [self.tableView reloadData];
}

- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    
    searcher.delegate=nil;
    self.geoCodeSearch=nil;
    
    if(error!=BMK_SEARCH_NO_ERROR){
        [SVProgressHUD showErrorWithStatus:@"定位失败"];
        self.positionData=@[@{@"name":@"定位失败"}];
        [self.tableView reloadData];
        return;
    }
    NSLog(@"province=%@",result.addressDetail.province);
    NSLog(@"city=%@",result.addressDetail.city);
    NSLog(@"district=%@",result.addressDetail.district);
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if(result.address.length!=0&&result.addressDetail.city.length!=0&&result.addressDetail.district.length!=0){
            NSMutableString *pinyin = [[NSMutableString alloc] initWithString:result.addressDetail.city];
            if (CFStringTransform((__bridge CFMutableStringRef)pinyin, 0, kCFStringTransformMandarinLatin, NO)) {
            }
            if (CFStringTransform((__bridge CFMutableStringRef)pinyin, 0, kCFStringTransformStripDiacritics, NO)) {
            }
            NSString *key=[[pinyin substringWithRange:NSMakeRange(0, 1)] uppercaseString];
            NSArray *arr=self.data[key];
            NSMutableString *strM=[[NSMutableString alloc]initWithString:result.addressDetail.city];
            if([strM hasSuffix:@"市"]){
                [strM deleteCharactersInRange:NSMakeRange(strM.length-1, 1)];
            }
            NSString *preStr=[NSString stringWithFormat:@"name LIKE[cd] '*%@*'",strM];
            NSPredicate *pre=[NSPredicate predicateWithFormat:preStr];
            NSArray *resultArr=[arr filteredArrayUsingPredicate:pre];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if(resultArr.count!=0){
                    NSMutableDictionary *dicM=[[NSMutableDictionary alloc]initWithDictionary:[resultArr lastObject]];
                    [dicM setValue:result.addressDetail.district forKey:@"ext"];
                    self.positionData=@[dicM];
                    [self.tableView reloadData];
                }else{
                    self.positionData=@[@{@"name":@"定位失败"}];
                    [self.tableView reloadData];
                }
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                self.positionData=@[@{@"name":@"定位失败"}];
                [self.tableView reloadData];
            });
            
        }

    });
    
}

#pragma mark - tableView
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 23)];
    view.backgroundColor=[UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH-10, view.height)];
    label.backgroundColor=[UIColor clearColor];
    label.textAlignment=NSTextAlignmentLeft;
    label.textColor=[UIColor colorWithRed:122/255.0 green:122/255.0 blue:122/255.0 alpha:1];
    [view addSubview:label];
    if(section==0){
        label.text=@"GPS定位";
    }else if (section==1){
        label.text=@"热门国内城市";
    }else{
        label.text=self.keys[section];
    }
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 23;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.keys.count;
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.keys;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section==0||section==1){
        return 1;
    }
    NSString *key=self.keys[section];
    NSArray *arr=self.data[key];
    return arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier=@"CellIdentifier";
    static NSString *HotCellIdentifier=@"HotCellIdentifier";
    if(indexPath.section==0){
        HotCityPositionTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:HotCellIdentifier forIndexPath:indexPath];
        cell.data=self.positionData;
        cell.delegate=self;
        [cell.collectionView reloadData];
        return cell;
    }
    if(indexPath.section==1){
        HotCityPositionTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:HotCellIdentifier forIndexPath:indexPath];
        cell.data=self.hotData;
        cell.delegate=self;
        [cell.collectionView reloadData];
        return cell;
    }
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    NSString *key=self.keys[indexPath.section];
    NSArray *arr=self.data[key];
    NSDictionary *dic=arr[indexPath.row];
    cell.textLabel.text=dic[@"name"];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section>1){
        NSString *key=self.keys[indexPath.section];
        NSArray *arr=self.data[key];
        NSDictionary *dic=arr[indexPath.row];
        if([self.delegate respondsToSelector:@selector(cityPositionExtViewController:indexPath:positionDic:)]){
            [self.delegate cityPositionExtViewController:self indexPath:indexPath positionDic:dic];
        }
    }
    //    NSString *key=self.keys[indexPath.section];
    //    NSArray *arr=self.data[key];
    //    NSDictionary *dic=arr[indexPath.row];
    //    CityPostionExtViewController *vc=[[CityPostionExtViewController alloc]init];
    //    vc.title=dic[@"p"];
    //    vc.data=dic[@"c"];
    //    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section==0){
        return [self getHeightOfHotCollectionViewWithArray:self.positionData];
    }
    if(indexPath.section==1){
        return [self getHeightOfHotCollectionViewWithArray:self.hotData];
    }else{
        return 44;
    }
}

-(CGFloat)getHeightOfHotCollectionViewWithArray:(NSArray *)array{
    int linesCount=0;
//    if(SCREEN_WIDTH>=414){
//        linesCount=(int)self.hotData.count/4;
//        if(self.hotData.count%4!=0){
//            linesCount++;
//        }
//
//    }else{
        linesCount=(int)array.count/3;
        if(array.count%3!=0){
            linesCount++;
        }
//    }
    return 10+10+linesCount*40+7*(linesCount-1);
}

#pragma mark - HotCityPositionTableViewCell
- (void)HotCityPositionTableViewCell:(HotCityPositionTableViewCell *)cell collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSIndexPath *tempIndexPath=[self.tableView indexPathForCell:cell];
    if(tempIndexPath.section==0){
        //定位
        NSString *str=self.positionData[0][@"name"];
        if([str isEqualToString:@"定位中"]||[str isEqualToString:@"定位失败"]){
            return;
        }
        if([self.delegate respondsToSelector:@selector(cityPositionExtViewController:indexPath:positionDic:)]){
            [self.delegate cityPositionExtViewController:self indexPath:tempIndexPath positionDic:self.positionData[0]];
        }
        return;
    }
    if(tempIndexPath.section==1){
        //热门城市
        if([self.delegate respondsToSelector:@selector(cityPositionExtViewController:indexPath:positionDic:)]){
            [self.delegate cityPositionExtViewController:self indexPath:tempIndexPath positionDic:self.hotData[indexPath.row]];
        }
        return;
    }
    
}
@end
